package com.longcai.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.longcai.bean.ApiResult;
import com.longcai.bean.PageHelper;
import com.longcai.config.rabbitmq.ExchangeConfig;
import com.longcai.config.rabbitmq.RabbitMqConfig;
import com.longcai.constants.OrderConstants;
import com.longcai.entity.customer.ClyjUser;
import com.longcai.entity.customer.customerVo.ClyjFuyouSmallcompanyRegistervo;
import com.longcai.entity.order.ClyjGoodsOrderDetails;
import com.longcai.entity.order.ClyjGoodsOrderInfo;
import com.longcai.mapper.ClyjGoodsOrderDetailsMapper;
import com.longcai.mapper.ClyjGoodsOrderInfoMapper;
import com.longcai.page.table.PageTableResponse;
import com.longcai.service.ClyjGoodsOrderDetailsService;
import com.longcai.util.order.OrderUtils;
import com.longcai.vo.ClyjGoodsOrderDetailsVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品订单表 服务实现类
 * </p>
 *
 * @author ZJ
 * @since 2019-04-19
 */
@Service
public class ClyjGoodsOrderDetailsServiceImpl implements ClyjGoodsOrderDetailsService {

    private static final Logger logger = LoggerFactory.getLogger(ClyjGoodsOrderDetailsServiceImpl.class);
    @Autowired
    public ClyjGoodsOrderInfoMapper clyjGoodsOrderInfoMapper;
    @Autowired
    private ClyjGoodsOrderDetailsMapper clyjGoodsOrderDetailsMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private ExchangeConfig exchangeConfig;

    /**
     * 创建订单
     *
     * @return
     */
    @Override
    public ApiResult<?> createOrder(ClyjUser clyjUser, ClyjGoodsOrderDetailsVo clyjGoodsOrderDetailsVo, List<ClyjFuyouSmallcompanyRegistervo> touches) {
        ApiResult<?> result = this.initOrder(clyjUser, clyjGoodsOrderDetailsVo, touches);
        // 创建订单
        ClyjGoodsOrderDetailsVo orderDetailsVo = (ClyjGoodsOrderDetailsVo) result.getData();
        // 获取订单
        List<ClyjGoodsOrderDetails> clyjGoodsOrderDetails = orderDetailsVo.getClyjGoodsOrderDetails();
        // 过滤商品订单
        List<ClyjGoodsOrderDetails> oderCache = clyjGoodsOrderDetails.stream()
                .filter(ClyjGoodsOrderDetails -> (OrderConstants.ORDER_TYPE_6 != ClyjGoodsOrderDetails.getOrderType()))
                .collect(Collectors.toList());

        if (orderDetailsVo != null && clyjGoodsOrderDetails.size() != 0) {
            // 将创建的订单加入到消息队列中，等待消费
            rabbitTemplate.convertAndSend(exchangeConfig.EXCHANGE_01, RabbitMqConfig.ROUTING_KEY_1, orderDetailsVo);

            logger.info("服务提供:{}", clyjGoodsOrderDetails.toString());
            return ApiResult.success("订单创建成功", oderCache);
        } else {
            return ApiResult.fail("订单创建失败");
        }
    }

    /**
     * 获取用户订单
     *
     * @param userId
     * @return
     */
    @Override
    public List<ClyjGoodsOrderDetails> selectByUserId(String userId) {

        return this.clyjGoodsOrderDetailsMapper.selectByUserId(userId);
    }

    /**
     * 初始化订单
     *
     * @return
     */
    public ApiResult<?> initOrder(ClyjUser clyjUser, ClyjGoodsOrderDetailsVo clyjGoodsOrderDetailsVo, List<ClyjFuyouSmallcompanyRegistervo> touches) {
        List<ClyjGoodsOrderDetails> list = clyjGoodsOrderDetailsVo.getClyjGoodsOrderDetails();
        LinkedList<ClyjGoodsOrderDetails> linkedList = new LinkedList<>();
        list.stream().forEach(l -> {
            // 商品订单
            ClyjGoodsOrderDetails clyjGoodsOrderDetails = new ClyjGoodsOrderDetails();

            clyjGoodsOrderDetails.setId((long) Math.abs(UUID.randomUUID().hashCode()));
            clyjGoodsOrderDetails.setTradeNo(OrderUtils.generateTradeNo());
            clyjGoodsOrderDetails.setUserId(clyjUser.getUserId());
            clyjGoodsOrderDetails.setGoodsId(l.getGoodsId());
            clyjGoodsOrderDetails.setGoodsName(l.getGoodsName());
            clyjGoodsOrderDetails.setSpecId(l.getSpecId());
            clyjGoodsOrderDetails.setGoodsSpec(l.getGoodsSpec());
            clyjGoodsOrderDetails.setOrderStatus(OrderConstants.ORDER_STATUS_0);
            clyjGoodsOrderDetails.setOrderType(l.getOrderType());
            clyjGoodsOrderDetails.setGoodsPrice(l.getGoodsPrice());
            clyjGoodsOrderDetails.setPayMoney(l.getPayMoney());
            clyjGoodsOrderDetails.setPayAmount(l.getPayAmount());
            clyjGoodsOrderDetails.setPayBalance(l.getPayBalance());
            clyjGoodsOrderDetails.setPayIntegral(l.getPayIntegral());
            clyjGoodsOrderDetails.setPayRedPacket(l.getPayRedPacket());
            clyjGoodsOrderDetails.setPayCoupon(l.getPayCoupon());
            clyjGoodsOrderDetails.setOrderSource(l.getOrderSource());
            clyjGoodsOrderDetails.setPayType(l.getPayType());
            clyjGoodsOrderDetails.setPayStatus(OrderConstants.PAY_TYPE_0);
            clyjGoodsOrderDetails.setPayUser(l.getPayUser());
            clyjGoodsOrderDetails.setGoodsAmount(l.getGoodsAmount());
            clyjGoodsOrderDetails.setRemark(l.getRemark());
            clyjGoodsOrderDetails.setPostFee(l.getPostFee());
            clyjGoodsOrderDetails.setSendMode(l.getSendMode());
            clyjGoodsOrderDetails.setShopsId(l.getShopsId());
            clyjGoodsOrderDetails.setShopsName(l.getShopsName());
            clyjGoodsOrderDetails.setMchId(l.getMchId());
            clyjGoodsOrderDetails.setReceiver(l.getReceiver());
            clyjGoodsOrderDetails.setReceiverAddress(l.getReceiverAddress());
            clyjGoodsOrderDetails.setReceiverPhone(l.getReceiverPhone());
            clyjGoodsOrderDetails.setCreateTime(System.currentTimeMillis());
            clyjGoodsOrderDetails.setUpdateTime(System.currentTimeMillis());
            clyjGoodsOrderDetails.setPayTime(System.currentTimeMillis());

            if (touches != null || touches.size() != 0) {
                touches.stream().forEach(t -> {
                    // 分润订单
                    ClyjGoodsOrderDetails details = new ClyjGoodsOrderDetails();

                    if (t.getUserId() != null) {
                        details = (ClyjGoodsOrderDetails) clyjGoodsOrderDetails.clone();
                        details.setId((long) Math.abs(UUID.randomUUID().hashCode()));
                        details.setUserId(t.getUserId());
                        details.setTradeNo(OrderUtils.generateTradeNo());
                        details.setPTradeNo(clyjGoodsOrderDetails.getTradeNo());
                        details.setGoodsId(clyjGoodsOrderDetails.getGoodsId());
                        details.setOrderType(OrderConstants.ORDER_TYPE_6);
                        details.setPayAmount(BigDecimal.ZERO);
                        details.setMchId("19920000379");
                        details.setCreateTime(System.currentTimeMillis());
                        details.setUpdateTime(System.currentTimeMillis());
                        details.setPayTime(System.currentTimeMillis());

                        linkedList.add(details);
                    }
                });
            }

            linkedList.add(clyjGoodsOrderDetails);
        });
        clyjGoodsOrderDetailsVo.setClyjGoodsOrderDetails(linkedList);
        return ApiResult.success(clyjGoodsOrderDetailsVo);
    }

    @Override
    public PageTableResponse selectByShopsId(JSONObject params, PageHelper pageHelper) {
        String shopsId = params.getString("shopsId");
        if (shopsId == null && shopsId.equals("")) {
            return new PageTableResponse(0, 0, null);
        }
        int i = this.clyjGoodsOrderDetailsMapper.selectCountByShopId(shopsId);
        Integer start = pageHelper.getStart();
        Integer length = pageHelper.getLength();
        Map<String, Object> map = new HashMap();
        map.put("start", start);
        map.put("length", length);
        map.put("shopsId", shopsId);
        map.put("orderType", params.getString("orderType"));
        map.put("orderStatus", params.getString("orderStatus"));
        map.put("tradeNo", params.getString("tradeNo"));
        map.put("userId", params.getString("userId"));
        map.put("startTime", params.getString("startTime"));
        map.put("endTime", params.getString("endTime"));
        map.put("updateStartTime", params.getString("updateStartTime"));
        map.put("updateEndTime", params.getString("updateEndTime"));
        List<ClyjGoodsOrderDetails> list = this.clyjGoodsOrderDetailsMapper.selectOrderListToPage(map);
        PageTableResponse pageTableResponse = new PageTableResponse(i, i, list);
        return pageTableResponse;
    }

    @Override
    public PageTableResponse selectByShopsId(String shopId, PageHelper pageHelper) {
        return null;
    }

    @Override
    public ApiResult<?> selectOrderBytradeNo(String tradeNo) {
        ClyjGoodsOrderDetails clyjGoodsOrderDetails = clyjGoodsOrderDetailsMapper.selectBytradeNo(tradeNo);
        return ApiResult.success(clyjGoodsOrderDetails);
    }

    @Override
    public ApiResult<?> updateOrderInfo(Map<String, Object> map) {
        //获取订单号
        if (map.get("tradeNo") == null) {
            return ApiResult.fail("订单号为空");
        }
        int update = this.clyjGoodsOrderDetailsMapper.updateOrder(map);
        if (update > 0) {
            return ApiResult.success();
        }
        return ApiResult.fail("更新失败");
    }

    /**
     * 取消订单
     *
     * @param trade_no
     * @return
     */
    @Override
    public ApiResult<?> cancelOrder(String trade_no) {
        try {
            ClyjGoodsOrderInfo clyjGoodsOrderInfo = new ClyjGoodsOrderInfo();
            clyjGoodsOrderInfo.setOrderStatus(OrderConstants.ORDER_STATUS_4);
            clyjGoodsOrderInfo.setTradeNo(trade_no);
            this.clyjGoodsOrderInfoMapper.updateByOrderNo(clyjGoodsOrderInfo);
            return ApiResult.success("订单取消成功");
        } catch (Exception e) {
            logger.error("---->>>>>订单取消失败", e);
        }
        return ApiResult.fail("订单取消失败，请重新尝试！");
    }
}